/**
 * 修改运费模板
 */
import React, {Component} from 'react';
import 'antd/dist/antd.css';
import {requestUrl, goods, template, china} from '../../value';
import app from '../../app';
import {
    Button,
    Form,
    Input,
    Icon,
    Row,
    Table,
    Col,
    Select,
    message,
    InputNumber,
    Checkbox,
    Modal,
    Radio,
    Tree
} from 'antd';
import moment from 'moment';
import {config} from '../../config';
import data from '../JSON/city.json';

const path = config.path;
const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;
const confirm = Modal.confirm;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;

class EditTransport extends Component {
    constructor(props) {
        super(props);
        this.state = {
            parentData: {
                template_shipping: '1'
            },
            noShippingLoading: false,
            first: '',  //首件、首重、首体积的单位变化
            addOrigin: '',  //续件、续重、续体积的单位变化
            cityData: [],
            districtCheck: false,  //是否选中复选框
            alertTransport: 'none',  //是否弹出为指定地区设置运费的页面

            childValue: [],  //获取子组件地区
            count: 0,  //给指定地区一个key


            firstPrecion: 0,  //按件数按体积按重量时首件和首体积手重量的小数位数不一样
            secondPrecion: 0,  //按件数按体积按重量时首件和首体积手重量的小数位数不一样
        }
    }

    formItemLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 8},
    };

    formAttentionItemLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 18},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        // 包邮
        if (this.state.parentData.template_shipping == '1') {
            return (
                <span>
                <Row>
                    <Row className='titleSize btnBottom'>修改运费模板</Row>
                    <Row style={{display: 'flex', marginBottom: '20px'}}>
                        <Col span={24}>
                            <Form className="login-form">
                                    <FormItem label={"模板名称:"} {...this.formItemLayout}>
                                        {getFieldDecorator('template_name', {
                                            rules: [{required: true, message: '请输入模板名称!'}],
                                        })(
                                            <Input placeholder="请输入"/>
                                        )}
                                    </FormItem>

                                    <FormItem label={"发货时间:"} {...this.formItemLayout}>
                                        {getFieldDecorator('template_time', {
                                            rules: [{required: true, message: '请选择发货时间!'}],
                                        })(
                                            <Select style={{width: '200px'}}>
                                                <Option value="12">12小时</Option>
                                                <Option value="24">24小时</Option>
                                                <Option value="48">48小时</Option>
                                            </Select>
                                        )}
                                    </FormItem>

                                <Col offset={2} span={22} className='btnBottom'>
                                    <span>注意:</span>
                                    <span>如实设定宝贝的发货时间，不仅可避免发货咨询和纠纷，还能促进成交</span>
                                </Col>

                                    <FormItem label={"是否包邮:"} {...this.formItemLayout}>
                                        {getFieldDecorator('template_shipping')(
                                            <span>卖家承担运费</span>
                                        )}
                                    </FormItem>
                            </Form>

                            {/*卖家承担运费*/}
                            <Col offset={2} span={22}>
                                    <Col span={6}><Button loading={this.state.noShippingLoading} onClick={() => {
                                        this.handleSaveShipping()
                                    }} type="primary">保存并返回</Button></Col>
                                    <Col span={6}> <Button onClick={() => {
                                        this.handleCancel()
                                    }} type="danger">取消</Button></Col>
                                </Col>
                        </Col>

                    </Row>

                </Row>
            </span>
            );
        }

        // 不包邮
        else {
            return (
                <span>
                <Row>
                    <Row className='titleSize btnBottom'>修改运费模板</Row>
                      <Row style={{display: 'flex', marginBottom: '20px'}}>
                        <Col span={24}>
                            <Form className="login-form">
                                    <FormItem label={"模板名称"} {...this.formItemLayout}>
                                        {getFieldDecorator('template_name', {
                                            rules: [{required: true, message: '请输入模板名称!'}],
                                        })(
                                            <Input placeholder="请输入"/>
                                        )}
                                    </FormItem>

                                    <FormItem label={"发货时间"} {...this.formItemLayout}>
                                        {getFieldDecorator('template_time', {
                                            rules: [{required: true, message: '请选择发货时间!'}],
                                        })(
                                            <Select style={{width: '200px'}}>
                                                <Option value="12">12小时</Option>
                                                <Option value="24">24小时</Option>
                                                <Option value="48">48小时</Option>
                                            </Select>
                                        )}
                                    </FormItem>
                                    <FormItem label={"注意"} {...this.formAttentionItemLayout}>
                                        {(
                                            <span>如实设定宝贝的发货时间，不仅可避免发货咨询和纠纷，还能促进成交</span>
                                        )}
                                    </FormItem>
                                    <FormItem label={"是否包邮"} {...this.formItemLayout}>
                                        {getFieldDecorator('template_shipping')(
                                            <span>自定义运费</span>
                                        )}
                                    </FormItem>
                                    <FormItem label={"运送方式"} {...this.formItemLayout}>
                                    {getFieldDecorator('template_method', {
                                        rules: [{required: true, message: '请选择运送方式!'}],
                                    })(
                                        <RadioGroup>
                                            <Radio value={'0'}>快递</Radio>
                                            <Radio value={'1'}>EMS</Radio>
                                            <Radio value={'2'}>平邮</Radio>
                                        </RadioGroup>
                                    )}
                                </FormItem>

                                {/*根据运送方式选择计价方式*/}
                                <FormItem label={"请先选择计价方式"} {...this.formItemLayout}>
                                    {getFieldDecorator('template_type', {
                                        rules: [{required: true, message: '请选择计价方式!'}],
                                    })(
                                        <RadioGroup onChange={(e) => {
                                            this.selectCostWay(e)
                                        }}>
                                            <Radio value={'0'}>按件数</Radio>
                                            <Radio value={'1'}>按重量</Radio>
                                            <Radio value={'2'}>按体积</Radio>
                                        </RadioGroup>
                                    )}
                                </FormItem>

                                <div style={{color: 'red', marginLeft: '50px'}}>默认运费</div>

                                              <FormItem label={this.state.first} {...this.formItemLayout}>
                                                {getFieldDecorator('template_firstNumber', {
                                                    rules: [{required: true, message: '请输入'}],
                                                })(
                                                    <InputNumber precision={this.state.firstPrecion} min={0}
                                                                 placeholder="请输入"/>
                                                )}
                                            </FormItem>

                                             <FormItem label={'首费'} {...this.formItemLayout}>
                                                {getFieldDecorator('template_firstPrice', {
                                                    rules: [{required: true, message: '请输入首费!'}],
                                                })(
                                                    <InputNumber min={0} precision={2} placeholder="请输入"/>
                                                )}
                                            </FormItem>

                                              <FormItem label={this.state.addOrigin} {...this.formItemLayout}>
                                                {getFieldDecorator('template_lastNumber', {
                                                    rules: [{
                                                        required: true,
                                                        message: '请输入'
                                                    }],
                                                })(
                                                    <InputNumber precision={this.state.secondPrecion} min={0}
                                                                 placeholder="请输入"/>
                                                )}
                                            </FormItem>

                                                <FormItem label={"续费(元)"} {...this.formItemLayout}>
                                                {getFieldDecorator('template_lastPrice', {
                                                    rules: [{required: true, message: '请输入续费!'}],
                                                })(
                                                    <InputNumber min={0} precision={2} placeholder="请输入"/>
                                                )}
                                            </FormItem>
                            </Form>

                            <Col offset={2} className='btnBottom'>
                                 <Checkbox
                                     checked={this.state.districtCheck}
                                     onClick={(e) => {
                                         this.handelControlAdd(e)
                                     }} value={'1'}>为指定地区设置运费</Checkbox>

                                 <DistrictPosts
                                     {...{cityData: this.state.cityData}}
                                     {...{first: this.state.first}}
                                     {...{second: this.state.addOrigin}}
                                     {...{firstPrecion: this.state.firstPrecion}}
                                     {...{secondPrecion: this.state.secondPrecion}}
                                     getDistrictPost={(value) => {
                                         this.getChildDistrictPost(value)
                                     }}

                                     alertTransport={this.state.alertTransport}/>
                            </Col>

                            {/*自定义运费运费*/}
                            <Col offset={2} span={22}>
                                    <Col span={6}><Button
                                        loading={this.state.noShippingLoading}
                                        onClick={() => {
                                            this.handleSaveNoShipping()
                                        }} type="primary">保存并返回</Button></Col>
                                    <Col span={6}> <Button onClick={() => {
                                        this.handleCancel()
                                    }} type="danger">取消</Button></Col>
                                </Col>
                        </Col>

                    </Row>

                </Row>
            </span>
            );
        }
    }

    handleSearchAllCity() {
        return app.post(china.SEARCH_ADDRESS_LIST, {}).then((body) => {
            if (body.code == 1) {

                let parentData = app.getData('editTransport');
                let arr = [];
                parentData.areaList.forEach((item, index) => {
                    let arr1 = item.template_area_content.split(',');
                    arr = arr.concat(arr1);
                });

                body.data.forEach((OptionsItem, OptionsIndex) => {
                    arr.forEach((item, index) => {
                        if (item == OptionsItem.id) {
                            OptionsItem.disabled = true;
                        } else {
                            OptionsItem.sub.forEach((OpCity, Opindex) => {
                                if (item == OpCity.id) {
                                    OpCity.disabled = true;
                                } else {
                                    OpCity.sub.forEach((OpArea, OpAIndex) => {
                                        if (item == OpArea.id) {
                                            OpArea.disabled = true;
                                        }
                                    })
                                }
                            })
                        }
                    })
                });

                this.setState({cityData: body.data});
            }
        })
    }

    componentDidMount() {
        //查出所有省市区
        this.handleSearchAllCity().then(() => {
            let parentData = app.getData('editTransport');
            let formData = [];
            let first;
            let addOrigin;
            let districtCheck;// 指定地区的复选框是否选中
            let alertTransport;
            let firstPrecion = 0;
            let secondPrecion = 0;
            if (parentData.areaList) {
                for (let i = 0; i < parentData.areaList.length; i++) {
                    parentData.areaList[i].template_area_id = parentData.areaList[i].template_area_content;
                }
            }
            if (parentData.template_shipping === '2') {
                parentData.template_shipping = '0';
            }
            parentData.template_method = (Number(parentData.template_method) - 1).toString();
            parentData.template_type = (Number(parentData.template_type) - 1).toString();
            message.config({
                top: '30%',
                duration: 2,
            });
            formData['template_name'] = {value: parentData.template_name};
            formData['template_time'] = {value: parentData.template_time + ''};

            // 不包邮的情况
            if (parentData.template_shipping == '0') {
                //默认运费的单位的显示
                if (parentData.template_type == '0') {
                    first = '首件数(件)';
                    addOrigin = '续件数(件)';
                    firstPrecion = 0;
                    secondPrecion = 0;
                }
                if (parentData.template_type == '1') {
                    first = '首重(kg)';
                    addOrigin = '续重(kg)';
                    firstPrecion = 3;
                    secondPrecion = 3;
                }
                if (parentData.template_type == '2') {
                    first = '首体积(m3)';
                    addOrigin = '续体积(m3)';
                    firstPrecion = 2;
                    secondPrecion = 2;
                }

                // 是否有指定地区的值来控制复选框是否选中，是否显示页面
                if (parentData.areaList.length > 0) {
                    districtCheck = true;
                    alertTransport = 'block'
                }
                if (parentData.areaList.length == 0) {
                    districtCheck = false;
                    alertTransport = 'none'
                }

                formData['template_method'] = {value: parentData.template_method};
                formData['template_type'] = {value: parentData.template_type};
                formData['template_firstNumber'] = {value: parentData.template_firstNumber};
                formData['template_lastNumber'] = {value: parentData.template_lastNumber};
                formData['template_firstPrice'] = {value: parentData.template_firstPrice};
                formData['template_lastPrice'] = {value: parentData.template_lastPrice};
            }

            this.props.form.setFields(formData);

            this.setState({
                parentData: parentData,
                first: first,
                addOrigin: addOrigin,
                districtCheck: districtCheck,  //指定地区的复选框是否选中
                alertTransport: alertTransport,
                firstPrecion: firstPrecion,
                secondPrecion: secondPrecion
            })
        });

    }

    // 请求修改运费
    requestEdit(values) {
        this.setState({noShippingLoading: true});
        app.post(template.UPDATE_TEMPLATE, values).then(req => {
            this.setState({noShippingLoading: false});
            if (req.code === 1) {
                this.props.history.push(path + '/home/transportTemplate'); //运费模板列表
                app.alert('修改成功', 'success', 3);
            } else {
                app.alert(req.msg, 'error', 3);
            }
        })
    }

    //免邮的修改运费
    handleSaveShipping() {
        let parentData = this.state.parentData;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.template_id = parentData.template_id;
                values.template_shipping = parentData.template_shipping;
                this.requestEdit(values);
            }
        })
    }

    // 获取子组件获取的指定地区的运费
    getChildDistrictPost(value) {
        this.setState({
            childValue: value
        })
    }

    // 不包邮的修改运费
    handleSaveNoShipping() {
        let districtCost = this.state.childValue;
        let districtCheck = this.state.districtCheck;
        let districtData = [];  //指定地区的所有运费
        let parentData = this.state.parentData;
        let cityData = this.state.cityData;
        let result;
        let temp;
        let count = 0;
        let that = this;

        this.props.form.validateFields((err, values) => {
            if (!err) {

                for (let h = 0; h < districtCost.length; h++) {
                    let occurProvince = districtCost[h].occurProvince;
                    for (let i = (occurProvince.length - 1); i >= 0; i--) {
                        for (let j = 0; j < cityData.length; j++) {
                            if (occurProvince[i] == cityData[j].id) {
                                occurProvince.splice(i, 1);
                                break;
                            } else {
                                for (let k = 0; k < cityData[j].sub.length; k++) {
                                    if (occurProvince[i] == cityData[j].sub[k].id) {
                                        occurProvince.splice(i, 1);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                values.template_shipping = '2';  //是否包邮
                values.template_id = parentData.template_id;
                // 选择了地区
                if (districtCheck) {
                    // 有修改过地区
                    if (districtCost.length > 0) {
                        districtCost.forEach((item) => {
                            count = count + 1;
                            // 把没有设置地区的运费排除
                            if (item.province != '请设置地区') {
                                result = item.province.search(',');  //判断是否只选择了一个地区
                                // 如果有多个地区
                                if (result > 0) {
                                    let id = '';
                                    // if(item.province.length == 1){
                                    //     item.province.split(',').forEach((dataItem, indes) => {
                                    //         id += dataItem + ',';
                                    //     });
                                    //     id = id.substring(0,id.length-1);
                                    // }else{
                                    //     item.province.forEach((dataItem, indes) => {
                                    //         id += dataItem + ',';
                                    //     });
                                    //     id = id.substring(0,id.length-1);
                                    // }
                                    item.occurProvince.forEach((dataItem, indes) => {
                                        id += dataItem + ',';
                                    });
                                    id = id.substring(0, id.length - 1);

                                    //循环得出区名字
                                    let cityData = that.state.cityData;
                                    let yetId = [];
                                    let yetName = '';
                                    cityData.map((p_item) => {
                                        p_item.sub.map(c_item => {
                                            c_item.sub.map(a_item => {
                                                item.occurProvince.map(o_item => {
                                                    if ((o_item == a_item.id) && (yetId.indexOf(o_item) == -1)) {
                                                        yetId.push(o_item);
                                                        yetName += a_item.name + ',';
                                                    }
                                                })
                                            })
                                        })
                                    });
                                    yetName = yetName.substring(0, yetName.length - 1);

                                    temp = {
                                        template_area_content: id,
                                        template_area_text: yetName,
                                        template_area_firstNumber: item.first,
                                        template_area_firstPrice: item.firstCost,
                                        template_area_lastNumber: item.second,
                                        template_area_lastPrice: item.secondCost,
                                        template_area_key: count,  //供查询的时候根据这个来查找地区
                                    };
                                    districtData.push(temp);
                                }
                                // 如果只有一个地区,用split方法会报错
                                else {
                                    let id = '';
                                    item.occurProvince.forEach((dataItem, indes) => {
                                        id += dataItem + ',';
                                    });
                                    id = id.substring(0, id.length - 1);

                                    //循环得出区名字
                                    let cityData = that.state.cityData;
                                    let yetId = [];
                                    let yetName = '';
                                    cityData.map((p_item) => {
                                        p_item.sub.map(c_item => {
                                            c_item.sub.map(a_item => {
                                                item.occurProvince.map(o_item => {
                                                    if ((o_item == a_item.id) && (yetId.indexOf(o_item) == -1)) {
                                                        yetId.push(o_item);
                                                        yetName += a_item.name + ',';
                                                    }
                                                })
                                            })
                                        })
                                    });
                                    yetName = yetName.substring(0, yetName.length - 1);

                                    temp = {
                                        template_area_content: id,
                                        template_area_text: yetName,
                                        template_area_firstNumber: item.first,
                                        template_area_firstPrice: item.firstCost,
                                        template_area_lastNumber: item.second,
                                        template_area_lastPrice: item.secondCost,
                                        template_area_key: count,  //供查询的时候根据这个来查找地区
                                    }
                                    districtData.push(temp);
                                }
                            }
                            values.areaList = JSON.stringify(districtData);  //所有指定地区的运费
                        })
                    }

                    // 没有修改过地区
                    else {
                        districtData = parentData.areaList;
                        values.areaList = JSON.stringify(districtData);  //所有指定地区的运费


                    }
                    // 复选框选中地区并有设置运费
                    if (districtData.length > 0) {
                        values.template_isArea = '1';
                    }

                    //复选框选中地区但是没有设置运费
                    if (districtData.length == 0) {
                        values.template_isArea = '2';
                    }
                }

                //没有选择地区
                if (!districtCheck) {
                    values.template_isArea = '2'
                }
                values.template_method = (Number(values.template_method) + 1).toString();
                values.template_type = (Number(values.template_type) + 1).toString();
                this.requestEdit(values);
            }
        })
    }

// 点击计价方式(控制默认运费的显示文字)
    selectCostWay(e) {
        let type = e.target.value;
        let first = '';
        let addOrigin = '';
        let firstPrecion = 0;
        let secondPrecion = 0;
        //按件数
        if (type == '0') {
            first = '首件数（件）';
            addOrigin = '续件数（件）';
            firstPrecion = 0;
            secondPrecion = 0;
        }

        //按重量
        if (type == '1') {
            first = '首重（kg）';
            addOrigin = '续重量（kg）';
            firstPrecion = 3;
            secondPrecion = 3;
        }

        //按体积
        if (type == '2') {
            first = '首体积（m3）';
            addOrigin = '续体积（m3）';
            firstPrecion = 2;
            secondPrecion = 2;
        }

        this.setState({
            costVisible: 'block',
            first: first,
            addOrigin: addOrigin,
            firstPrecion: firstPrecion,
            secondPrecion: secondPrecion
        })
    }

// 点击为指定地区设置默认运费的按钮
    handelControlAdd(e) {
        let alertTransport;
        let check = e.target.checked;
        if (check) {
            alertTransport = 'block'
        } else {
            alertTransport = 'none'
        }
        this.setState({
            districtCheck: check,
            alertTransport: alertTransport, //是否显示指定地区运费的页面
        })
    }

// 点击取消按钮
    handleCancel() {
        this.props.history.push(path + '/home/transportTemplate'); //运费模板列表
    }

}

// 为指定地区设置运费
class DistrictPost extends Component {
    constructor(props) {
        super(props);
        this.state = {
            provinces: [],
            selectProvice: [],  //选中的省
            costModal: false,
            data: [],
            count: 0,
            cityData: this.props.cityData,
            provinceList: [],
            parentData: [],  //数据库传的数据

            editData: {},
            editIndex: '',
            selectKey: [],
            allArea: [],
        };
    }


    render() {
        const {getFieldDecorator} = this.props.form;
        const {first, second, secondPrecion, firstPrecion} = this.props;
        const columns = [
            {
                title: '地区',
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <span>
                        <span
                            className='btnRight'>{data.chineseName != undefined ? data.chinese : data.province}...</span>
                         <Icon
                             className="editIcon"
                             type="edit"
                             style={{fontSize: '18px', color: 'red'}}
                             onClick={() => {
                                 this.handleCancel(true, data, index)
                             }}
                         />
                    </span>
                    )
                }
            },
            {
                title: first,
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <InputNumber precision={firstPrecion} min={0} value={data.first} onChange={(e) => {
                            this.handleCHangeFirst(e, index)
                        }} type='text'/>
                    )
                }
            },
            {
                title: '首费',
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <InputNumber
                            min={0} precision={2}
                            onChange={(e) => {
                                this.handleCHangeFirstCost(e, index)
                            }}
                            value={data.firstCost}
                            type='text'/>
                    )
                }
            },
            {
                title: second,
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <InputNumber min={0} precision={secondPrecion} value={data.second}
                                     onChange={(e) => {
                                         this.handleCHangeSecond(e, index)
                                     }}
                                     type='text'/>
                    )
                }
            },
            {
                title: '续费',
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <InputNumber min={0} precision={2}
                                     onChange={(e) => {
                                         this.handleCHangeSecondCost(e, index)
                                     }}
                                     value={data.secondCost} type='text'/>
                    )
                }
            },
            {
                title: '操作',
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <span>
                       <Button type='danger' onClick={(datas, indexs) => {
                           this.deleteDistrictCost(data, index)
                       }}>删除</Button>
                    </span>
                    )
                }
            },
        ];
        return (
            <div>
                  <span>
                     <Modal
                         maskClosable={false}
                         title={'为指定地区设置运费'}
                         wrapClassName="vertical-center-modal"
                         width={'600px'}
                         onOk={() => {
                             this.handleSubmit()
                         }}
                         visible={this.state.visible}
                         onCancel={() => {
                             this.handleCancel(false, '')
                         }}
                     >
                         <Row style={{height: '800px', overflow: 'scroll'}}>
                               <Col offset={1} span={23}>
                                   <Form>
                                        {/*<FormItem label={"选择地区"} {...this.formDistrictLayout}>*/}
                                       {/*{getFieldDecorator('specialDistrict', {*/}
                                       {/*rules: [{required: true, message: '请选择地区!'}],*/}
                                       {/*})(*/}
                                       {/*<CheckboxGroup options={this.state.provinceList}*/}
                                       {/*onChange={(value) => {*/}
                                       {/*this.onChangeDistrict(value)*/}
                                       {/*}}/>*/}
                                       {/*)}*/}
                                       {/*</FormItem>*/}

                                       <FormItem label={"选择地区"} {...this.formDistrictLayout}>

                                                        <Tree
                                                            checkable
                                                            onSelect={this.onSelect}
                                                            checkedKeys={this.state.selectKey}
                                                            onCheck={this.onCheck}
                                                        >
                                                            {
                                                                this.state.cityData.map((item, index) => {
                                                                    return (
                                                                        <TreeNode disabled={item.disabled}
                                                                                  title={item.name} key={item.id}>
                                                                            {
                                                                                item.sub.map((itemCity, indexCity) => {
                                                                                    return (
                                                                                        <TreeNode
                                                                                            disabled={itemCity.disabled}
                                                                                            title={itemCity.name}
                                                                                            key={itemCity.id}>
                                                                                            {
                                                                                                itemCity.sub.map((itemArea, indexArea) => {
                                                                                                    return (
                                                                                                        <TreeNode
                                                                                                            disabled={itemArea.disabled}
                                                                                                            title={itemArea.name}
                                                                                                            key={itemArea.id}/>
                                                                                                    )
                                                                                                })
                                                                                            }
                                                                                        </TreeNode>
                                                                                    )
                                                                                })
                                                                            }
                                                                        </TreeNode>

                                                                    )
                                                                })
                                                            }
                                                        </Tree>


                                        </FormItem>


                                   </Form>
                               </Col>
                         </Row>

                </Modal>
            </span>
                <Row style={{display: this.props.alertTransport}}>
                    <Col span={24}>
                        <Form className="login-form">
                            <Col span={24} style={{border: '1px solid #ddd', padding: '20px 0px'}}>
                                <Col offset={2} span={20}>
                                    <Button type='primary' onClick={() => {
                                        this.setModalVisible(true)
                                    }}>添加</Button>

                                    <Table
                                        columns={columns}
                                        rowKey={(record, index) => index}
                                        dataSource={this.state.data}
                                    />
                                </Col>
                            </Col>
                        </Form>
                    </Col>
                </Row>
            </div>
        )

    }

    handleSearchAllCity() {
        return app.post(china.SEARCH_ADDRESS_LIST, {}).then((req) => {
            if (req.code === 1) {
                const _this = this;
                let area = _this.state.allArea;
                req.data.forEach((item) => {
                    item.sub.forEach((items) => {
                        items.sub.forEach((itemArea) => {
                            area.push(itemArea)
                        })
                    })
                });
                _this.state.allArea = area;
                _this.setState({allArea: area});
                this.setState({cityData: req.data});
            }
        })
    }

    componentDidMount() {
        this.handleSearchAllCity().then(() => {
            let parentData = app.getData('editTransport');
            let count = this.state.count;
            let data = [];
            let lastKey = 0;

            if (parentData.areaList.length > 0) {
                lastKey = parentData.areaList[parentData.areaList.length - 1].template_area_key;
                for (let i = 1; i <= parentData.areaList.length; i++) {
                    let province = '';
                    let temp = {};
                    let checkProvince = [];
                    let allArea = this.state.allArea;
                    parentData.areaList.forEach((item) => {
                        if (item.template_area_key === i) {
                            province = item.template_area_content;
                            checkProvince = province.split(',');
                            let chinese = '';

                            let subList = province.substring(0, 27).split(",");

                            /*遍历求出中文名*/
                            allArea.forEach((itemID) => {
                                subList.forEach((items) => {
                                    if (items == itemID.id) {
                                        chinese += itemID.name + ',';
                                    }
                                })
                            });
                            chinese = chinese.substring(0, chinese.length - 1);

                            temp = {
                                id: item.template_area_key,
                                key: item.template_area_key,
                                // province: province.substring(0, province.length - 1),
                                province: chinese,
                                first: item.template_area_firstNumber,
                                firstCost: item.template_area_firstPrice,
                                second: item.template_area_lastNumber,
                                secondCost: item.template_area_lastPrice,
                                occurProvince: checkProvince
                            };
                        }
                    });
                    data.push(temp)
                }

            }

            this.setState({
                data: data,
                count: lastKey + 1,
                parentData: parentData
            });
        });


        // this.requestProvinces(); //查找所有的省
    }

    // 获取选中的地区
    onChangeDistrict(value) {
        this.setState({
            selectProvice: value
        })
    }

    handleCancel(visible, data, index) {
        let districtOptions = this.props.cityData;
        let parentData = this.state.parentData;
        let provinceList = this.state.provinceList;

        if (visible) {
            districtOptions.forEach((OptionsItem, OptionsIndex) => {
                data.occurProvince.forEach((itemPro, dataindex) => {
                    if (itemPro == OptionsItem.id) {
                        OptionsItem.disabled = false;
                    } else {
                        OptionsItem.sub.forEach((OpCity, Opindex) => {
                            if (itemPro == OpCity.id) {
                                OpCity.disabled = false;
                            } else {
                                OpCity.sub.forEach((OpArea, OpAIndex) => {
                                    if (itemPro == OpArea.id) {
                                        OpArea.disabled = false;
                                    }
                                })
                            }
                        })
                    }
                })
            })
        } else {
            districtOptions.forEach((OptionsItem, OptionsIndex) => {
                OptionsItem.disabled = true;
                OptionsItem.sub.forEach((OpCity, Opindex) => {
                    OpCity.disabled = true;
                    OpCity.sub.forEach((OpArea, OpAIndex) => {
                        OpArea.disabled = true;
                    })
                })
            })
        }

        let cityArr = [];
        if (data != "") {
            let cutData;
            if (data.occurProvince.length != 0) {
                if (data.occurProvince[0].length == 6) {
                    cutData = data.occurProvince[0].substring(0, data.occurProvince[0]);
                } else if (data.occurProvince[0].length >= 27) {
                    cutData = data.occurProvince[0].substring(0, data.occurProvince[0].length);
                }


            }
            if (data.occurProvince.length == 1) {
                cityArr = data.occurProvince[0].split(',');
            } else {
                cityArr = data.occurProvince;
            }

            this.state.selectKey = cityArr;
            this.setState({selectKey: cityArr});
        }


        let tableData = this.state.data;
        let disabledData = [];
        let disabledDataString = '';
        let isOne;  //判断是否只有一个地区；
        let formData = [];
        let occurProvince = [];  //复选框选中的
        if (visible) {
            tableData.forEach((item) => {
                disabledDataString += item.province + ',';
            });
            disabledDataString = disabledDataString.substring(0, disabledDataString.length - 1);
            isOne = disabledDataString.indexOf(',');

            // 如果有多个地区
            if (isOne) {
                disabledData = disabledDataString.split(',');
            } else {
                disabledData.push(disabledDataString);  //没有多个地区用split方法会出错
            }

            formData['specialDistrict'] = {value: data.occurProvince};
            this.props.form.setFields(formData);

        }
        this.setState({
            visible: visible,
            provinceList: provinceList,
            editData: data,
            editIndex: index
        })
    }


    onSelect = (selectedKeys, info) => {
        console.log('selected', selectedKeys, info);
        let provin = this.state.province;
        let flag = false;
        let pid = '';
        provin.forEach((item, index) => {
            if (item.id == selectedKeys) {
                flag = true;
            }
        });
        if (flag == true) {
            pid = provin.findIndex(function (item) {
                return item.id == selectedKeys
            });
            console.log(pid);
            app.post(china.SEARCH_ADDRESS_LIST, {token: app.getToken(), pid: selectedKeys[0]}).then((req) => {
                let province = this.state.province;

                if (req.code === 1) {
                    province[pid].sublist = req.data.sub;
                    this.state.pid = pid;
                    this.setState({province});
                    console.log(this.state.province);
                }
            });
        }


    };

    /*新的check方法*/
    onCheck = (checkedKeys, info) => {
        const _this = this;
        console.log('onCheck', checkedKeys, info);
        _this.state.allId = checkedKeys;
        this.setState({selectKey: checkedKeys});
        console.log(_this.state.allId);
    };

    // 获取首件数显示在文本框
    handleCHangeFirst = (value, index) => {
        let datasourse = this.state.data;
        datasourse[index].first = value;
        this.props.getDistrictPost(datasourse);  //传值给父类
        this.setState({
            data: datasourse
        })
    }

    // 获取首费用显示在文本框
    handleCHangeFirstCost = (value, index) => {
        let datasourse = this.state.data;
        datasourse[index].firstCost = value;
        this.props.getDistrictPost(datasourse);  //传值给父类
        this.setState({
            data: datasourse
        })
    }

    // 获取续件显示在文本框
    handleCHangeSecond = (value, index) => {
        let datasourse = this.state.data;
        datasourse[index].second = value;
        this.props.getDistrictPost(datasourse);  //传值给父类
        this.setState({
            data: datasourse
        })
    }

    // 获取续费显示在文本框
    handleCHangeSecondCost = (value, index) => {
        let datasourse = this.state.data;
        datasourse[index].secondCost = value;
        this.props.getDistrictPost(datasourse);  //传值给父类
        this.setState({
            data: datasourse
        })
    }

    // 删除某个设置的地区（并把删除对应的禁止解放）
    deleteDistrictCost(deleteData, index) {
        const dataSource = [...this.state.data];
        let parentData = this.state.parentData;
        let optionsReset = this.state.provinceList;
        let selectProvince = deleteData.province;
        let result = selectProvince.indexOf(',');
        let compareProvince = [];
        let temp;

        if (parentData.areaList.length > 0) {
            parentData.areaList.splice(index, 1);
        }
        if (deleteData.province != '请设置地区') {
            if (result > 0) {
                compareProvince = selectProvince.split(',');
            } else {
                compareProvince.push(selectProvince);
            }
            optionsReset.forEach((provinceItem) => {
                compareProvince.forEach((selectItem) => {
                    if (provinceItem.label == selectItem) {
                        provinceItem.disabled = false;
                    }
                })
            })
        }
        this.props.getDistrictPost(dataSource.filter(item => item.key !== deleteData.key));  //传值给父类
        this.setState({
            data: dataSource.filter(item => item.key !== deleteData.key),
            provinceList: optionsReset,
            parentData: parentData
        });
    }

    // 设置是否弹出设置运费框
    setModalVisible() {
        const {count, data} = this.state;
        let tableData = this.state.data;
        let flag = 0;
        if (tableData.length == 0) {
            const newData = {
                id: count,
                key: count,
                province: `请设置地区`,
                first: 0,
                firstCost: 0,
                second: 0,
                secondCost: 0,
                occurProvince: []
            };
            this.setState({
                data: [...data, newData],
                count: count + 1,
            });
        } else {
            tableData.forEach((item) => {
                if (item.province == '请设置地区') {
                    flag = 1;
                    message.info('请选择地区');
                    return false;
                }
            })

            if (flag == 0) {
                const newData = {
                    id: count,
                    key: count,
                    province: `请设置地区`,
                    first: 0,
                    firstCost: 0,
                    second: 0,
                    secondCost: 0,
                    occurProvince: []
                };
                this.setState({
                    data: [...data, newData],
                    count: count + 1,
                });
            }
        }
    }

    // 提交地区弹出框
    handleSubmit() {
        const _this = this;
        let count = this.state.count;
        let temp = '';
        let editData = this.state.editData;  //获取所点击的那条数据
        let editIndex = this.state.editIndex; //获取点击的数据的索引
        let selectProvince = this.props.form.getFieldValue('specialDistrict');
        let data = this.state.data;
        let checkarr = this.state.selectKey;
        let indexArr = [];
        let countArr = [];

        let cityData = this.props.cityData;
        cityData.forEach((itemid, itemindex) => {
            checkarr.forEach((cityDataId, ItemIndexId) => {
                if (itemid.id == cityDataId) {
                    itemid.disabled = true;
                } else {
                    itemid.sub.forEach((itemCity, ItemIndex) => {
                        if (itemCity.id == cityDataId) {
                            itemCity.disabled = true;
                        } else {
                            itemCity.sub.forEach((itemArea, AreaIndex) => {
                                if (itemArea.id == cityDataId) {
                                    itemArea.disabled = true;
                                } else {
                                }
                            })
                        }
                    })
                }
            })
        });

        for (let i = 0; i < indexArr.length; i++) {
            checkarr.splice(checkarr[indexArr[i]], 1);
        }
        console.log(checkarr);
        // indexArr.forEach((indexarr)=>{
        //     checkarr.splice(indexarr,1);
        // });

        let indexName = checkarr[0];
        let chineseName = '';

        this.state.cityData.forEach((area) => {
            if (area.id == indexName) {
                chineseName = area.name;
            } else {
                area.sub.forEach((area_sec) => {
                    if (area_sec.id == indexName) {
                        chineseName = area_sec.name;
                    } else {
                        area_sec.sub.forEach((area_thr) => {
                            if (area_thr.id == indexName) {
                                chineseName = area_thr.name;
                            }
                        })
                    }
                })
            }
        })


        checkarr.forEach((item, index) => {
            temp += item + ',';
        });
        temp = temp.substring(0, temp.length - 1);


        data[editIndex].province = temp;
        data[editIndex].chineseName = chineseName;
        data[editIndex].occurProvince = checkarr;

        this.props.getDistrictPost(data);

        this.setState({
            data: data,
            count: count + 1,
            visible: false
        })
    }
}


const DistrictPosts = Form.create()(DistrictPost);
const EditTransports = Form.create()(EditTransport);
export default EditTransports;